<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import * as admin from '@/api/admin.js'
import {ElMessageBox} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
//文章分类数据模型
const xiaochiList = ref([])

//用户搜索时选中的分类id
const name = ref('')

// //用户搜索时选中的发布状态
// const state = ref('')


//文章列表数据模型
const articles = ref([])

//分页条数据模型
const currentPage = ref(1)//当前页
const total = ref(5)//总条数
const pageSize = ref(10)//每页条数


const dialogVisible = ref(false)
const title = ref('修改店铺信息')
const categoryModel = ref({
    id: '',
    name: '',
    img: '',
    xiaoshiId: '',
    content: '',
    address: '',
    url: '',
})


//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    articleList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    currentPage.value = num
    articleList()
}

const getxiaochilist = async () => {
    let result = await admin.getXiaochi({});
    xiaochiList.value = result.data;
    console.log(xiaochiList.value);
}


//获取文章列表数据
const articleList = async () => {
    let params = {
        currentPage: currentPage.value,
        content: name.value,
    }
    console.log(params);
    let result = await admin.findPinlun(params);

    //渲染视图
    total.value = result.total;
    articles.value = result.data;
}

const showDialog = (row) => {
    Object.assign(categoryModel.value, row);
}

const updateJinqu = async() => {
    const result = await admin.updateDianpu(categoryModel.value);
    ElMessage.success(result.msg ? result.msg : '修改成功')
    dialogVisible.value = false;
    articleList();
}

const delData = async (row) => {
    ElMessageBox.confirm(
    '你确认要删除该评论信息吗?',
    '温馨提示',
    {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
    .then(async () => {
        try {
            // 调用接口
            const result = await admin.delpinlun({ id: row.id });
            if (result) {  // 假设 result 为删除成功的标志
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });
                articleList()
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败',
                });
                articleList()
            }
        } catch (error) {
            // console.error('删除操作失败:', error);
            ElMessage({
                type: 'error',
                message: '删除失败，请稍后再试。',
            });
        }
    })
    .catch(() => {
        console.log('取消删除');
        ElMessage({
            type: 'info',
            message: '取消删除',
        });
    });
    articleList();
}

getxiaochilist()

articleList();


//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const articleModel = ref({
    name: '',
    img: '',
    xiaoshiId: '',
    content: '',
    address: '',
    url: '',
})


//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

//上传成功的回调函数
const uploadSuccess = (result)=>{
    categoryModel.value.img = result.data;
    articleModel.value.img = result.data;
    console.log(categoryModel.value);
}
const formatDate = (date) => {
    if (!date) {
      return '';
    }
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); 
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

//添加文章
import {ElMessage} from 'element-plus'
const addArticle = async ()=>{
    //把发布状态赋值给数据模型
    // articleModel.value.state = clickState;

    //调用接口
    let result = await admin.addDianpu(articleModel.value);

    ElMessage.success(result.msg? result.msg:'添加成功');

    //让抽屉消失
    visibleDrawer.value = false;

    //刷新当前列表
    articleList()
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>评论管理</span>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="评论：">
                <el-input v-model="name"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="articleList">搜索</el-button>
                <el-button @click="name = '';">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="articles" style="width: 100%">
            <el-table-column label="用户" prop="userNickname"></el-table-column>
            <el-table-column label="评分" prop="fenshu"></el-table-column>
            <el-table-column label="评论内容" prop="content"></el-table-column>
            <el-table-column label="评论对象">
                <template #default="{ row }">
                    <template v-if="row.jinquId">景区：{{ row.jinquName }}</template>
                    <template v-if="row.dataName">酒店：{{ row.dataName }}</template>
                </template>
            </el-table-column>
            <el-table-column label="评论时间">
                <template #default="{ row }">
                    {{ formatDate(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Delete" circle plain type="danger" @click = "delData(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->

        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            @current-change="onCurrentChange"
            layout="prev, pager, next, jumper">
          </el-pagination>
        <!-- <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
            layout="jumper, total, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" /> -->

        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" title="添加店铺" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="articleModel" label-width="100px">
                <el-form-item label="店铺名称">
                    <el-input v-model="articleModel.name" placeholder="请输入店铺名称"></el-input>
                </el-form-item>
                <el-form-item label="美食"> 
                    <el-select v-model="articleModel.xiaoshiId" placeholder="请选择美食">
                        <el-option v-for="(item,index) in xiaochiList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                    <!-- <el-input v-model="articleModel.nickName" placeholder="请输入店铺别名"></el-input> -->
                </el-form-item>
                <el-form-item label="店铺图片">
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                    action="http://localhost:8080/upload/image"
                    name="file"
                    :headers="{'Authorization':tokenStore.token}"
                    :on-success="uploadSuccess"
                    >
                        <img v-if="articleModel.img" :src="articleModel.img" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="店铺描述">
                    <div class="editor">
                        <!-- <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html">
                        </quill-editor> -->
                        <textarea :rows="4" v-model="articleModel.content" style="width: 100%;" lable="景点描述" class="editor-textarea"></textarea>
                    </div>
                </el-form-item>
                <el-form-item label="店铺地址">
                    <el-input v-model="articleModel.address" placeholder="请输入店铺地址"></el-input>
                </el-form-item>
                <el-form-item label="地址链接">
                    <el-input v-model="articleModel.url" placeholder="请输入开放时间"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addArticle('添加店铺')">添加</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

         <!-- 添加分类弹窗 -->
         <el-dialog v-model="dialogVisible" :title="title" width="30%">
            <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-form-item label="店铺名称" prop="name">
                    <el-input v-model="categoryModel.name" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="所示美食" prop="xiaoshiId">
                    <el-select v-model="categoryModel.xiaoshiId" placeholder="请选择美食">
                        <el-option v-for="(item,index) in xiaochiList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="店铺地址" prop="address">
                    <el-input v-model="categoryModel.address" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="店铺描述" prop="content">
                    <el-input v-model="categoryModel.content" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="地址链接" prop="url">
                    <el-input v-model="categoryModel.url" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="img"  >
                    <el-upload
                        ref="upload"
                        class="upload-demo"
                        name="file"
                        action="http://localhost:8080/upload/image"
                        :on-success="uploadSuccess"
                        :show-file-list="false"
                        :auto-upload="true"
                        :before-upload="beforeUpload"
                        
                    >
                    <img v-if="categoryModel.img" :src="categoryModel.img" class="avatar" style="width: 100px; height: 100px; object-fit: cover;"  />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="updateJinqu()"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 分页 -->
        
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>